package com.framework.workflow.util;

import cn.hutool.core.collection.CollectionUtil;
import com.framework.common.config.SessionUtil;
import com.framework.workflow.constant.DataDict;
import com.framework.workflow.dto.NodeProperty;
import com.framework.workflow.params.CompleteParam;
import com.framework.workflow.params.StartParam;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * @author zjsg
 */
public class VariableUtil {
    public static void setCompleteVariables(Map<String, Object> variables, CompleteParam param) {
        String isReject = param.getIsReject();
        // 是否驳回
        variables.put(DataDict.WfVariableKey.IS_REJECT.toString(), isReject);
        if (param.getAttribute() != null && param.getAttribute().size() > 0) {
            variables.putAll(param.getAttribute());
        }
    }


    public static void setVariables(NodeProperty nodeProperty, Map<String, Object> variables, List<String> users) {
        if (CollectionUtil.isEmpty(users)) {
            return;
        }
        if (nodeProperty.isEnd()) {
            return;
        }
        // 设置默认参数
        if (isExpression(nodeProperty.getAssignee().get(0))) {
            // 处理人可以有多个用逗号隔开， 所以这里获取第一个判断是不是WfVariableKey.ASSIGNEE， 不是的话不用处理
            String express = nodeProperty.getAssignee().get(0);
            if (nodeProperty.isMulti()) {
                // 会签，并且配置了处理人是WfVariableKey.SELECT_ASSIGNEE，设置参数
                String collectionVariable = nodeProperty.getCollectionVariable();
                if (isExpression(express)) {
                    // 自动设置集合变量的参数， 前端可以随意配置
                    String variableItemName = collectionVariable.substring(2, collectionVariable.length() - 1);
                    variables.put(variableItemName, users);
                }
            } else {
                String variableName = express.substring(2, express.length() - 1);
                variables.put(variableName, users.get(0));
            }
        }
    }

    public static void setStartVariables(Map<String, Object> processVariables, StartParam startParam) {
        String startUserId = SessionUtil.getUser().getId();
        processVariables.put(DataDict.WfVariableKey.START_USER.toString(), startUserId);
        Map<String, Object> variables = startParam.getAttribute();
        if (variables != null && variables.size() > 0) {
            processVariables.putAll(variables);
        }
    }

    private static boolean isExpression(String expression) {
        String prefix = "${";
        String suffix = "}";
        if (StringUtils.isBlank(expression)) {
            return false;
        }
        expression = expression.trim();
        // 如果是变量返回null
        return expression.startsWith(prefix) && expression.endsWith(suffix);
    }

}
